package com.example.hanfu_bk.controller;

import com.example.hanfu_bk.pojo.User;
import com.example.hanfu_bk.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    // 头像上传路径（在application.properties中配置）
    @Value("${avatar.upload.path:/static/avatars/}")
    private String avatarUploadPath;

    // 头像访问基础URL
    @Value("${avatar.access.url:/avatars/}")
    private String avatarAccessUrl;

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User loginUser) {
        // 验证参数是否存在
        if (loginUser.getPhone() == null || loginUser.getPhone().isEmpty() ||
                loginUser.getPassword() == null || loginUser.getPassword().isEmpty()) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", 400);
            errorResult.put("msg", "手机号或密码不能为空");
            return errorResult;
        }

        Map<String, Object> result = new HashMap<>();
        User user = userService.login(loginUser.getPhone(), loginUser.getPassword());
        if (user != null) {
            result.put("code", 200);
            result.put("msg", "登录成功");
            result.put("data", user);
        } else {
            result.put("code", 400);
            result.put("msg", "手机号或密码错误");
        }
        return result;
    }

    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();

        int row = userService.register(user);
        if (row > 0) {
            result.put("code", 200);
            result.put("msg", "注册成功");
        } else if (row == -1) {
            result.put("code", 400);
            result.put("msg", "手机号已注册");
        } else {
            result.put("code", 500);
            result.put("msg", "注册失败");
        }
        return result;
    }

    // 找回密码接口（保持原有逻辑）
    @PostMapping("/resetPassword")
    public Map<String, Object> resetPassword(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();

        // 参数验证
        if (user.getPhone() == null || user.getPhone().isEmpty()) {
            result.put("code", 400);
            result.put("msg", "请输入手机号");
            return result;
        }

        // 执行密码重置
        int row = userService.resetPassword(user.getPhone(), user.getFavoriteThing(), user.getPassword());
        if (row > 0) {
            result.put("code", 200);
            result.put("msg", "密码重置成功");
        } else if (row == -1) {
            result.put("code", 400);
            result.put("msg", "手机号未注册");
        } else if (row == -2) {
            result.put("code", 400);
            result.put("msg", "密保答案不正确");
        } else {
            result.put("code", 500);
            result.put("msg", "密码重置失败");
        }
        return result;
    }


    @GetMapping("/info")
    public Map<String, Object> getUserInfo(@RequestParam Integer id) {
        Map<String, Object> result = new HashMap<>();
        User user = userService.getUserInfo(id);
        if (user != null) {
            result.put("code", 200);
            result.put("data", user);
        } else {
            result.put("code", 404);
            result.put("msg", "用户不存在");
        }
        return result;
    }

    @PostMapping("/logout")
    public Map<String, Object> logout(@RequestParam Integer id) {
        Map<String, Object> result = new HashMap<>();
        int row = userService.logout(id);
        if (row > 0) {
            result.put("code", 200);
            result.put("msg", "退出成功");
        } else {
            result.put("code", 500);
            result.put("msg", "退出失败");
        }
        return result;
    }


    @PostMapping("/update")
    public Map<String, Object> updateUserInfo(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        int row = userService.updateUserInfo(user);
        if (row > 0) {
            result.put("code", 200);
            result.put("msg", "更新成功");
        } else {
            result.put("code", 500);
            result.put("msg", "更新失败");
        }
        return result;
    }

    @PostMapping("/updatePassword")
    public Map<String, Object> updatePassword(@RequestBody Map<String, String> params) {
        Map<String, Object> result = new HashMap<>();

        // 解析参数
        Integer userId = params.get("id") != null ? Integer.parseInt(params.get("id")) : null;
        String oldPassword = params.get("oldPassword");
        String newPassword = params.get("newPassword");

        // 参数校验
        if (userId == null || oldPassword == null || oldPassword.isEmpty() ||
                newPassword == null || newPassword.isEmpty()) {
            result.put("code", 400);
            result.put("msg", "参数不完整");
            return result;
        }
        if (newPassword.length() < 6 || newPassword.length() > 16) {
            result.put("code", 400);
            result.put("msg", "新密码需6-16位");
            return result;
        }

        // 调用服务层（未加密逻辑）
        int row = userService.updatePassword(userId, oldPassword, newPassword);
        if (row > 0) {
            result.put("code", 200);
            result.put("msg", "密码修改成功");
        } else if (row == -1) {
            result.put("code", 400);
            result.put("msg", "原密码错误");
        } else if (row == -2) {
            result.put("code", 404);
            result.put("msg", "用户不存在");
        } else {
            result.put("code", 500);
            result.put("msg", "修改失败");
        }
        return result;
    }

    /**
     * 修改密保答案接口（未加密版本）
     */
    @PostMapping("/updateSecurityAnswer")
    public Map<String, Object> updateSecurityAnswer(@RequestBody Map<String, String> params) {
        Map<String, Object> result = new HashMap<>();

        // 解析参数
        Integer userId = params.get("id") != null ? Integer.parseInt(params.get("id")) : null;
        String password = params.get("password");
        String securityAnswer = params.get("securityAnswer");

        // 参数校验
        if (userId == null || password == null || password.isEmpty() ||
                securityAnswer == null || securityAnswer.isEmpty()) {
            result.put("code", 400);
            result.put("msg", "参数不完整");
            return result;
        }

        // 调用服务层（未加密逻辑）
        int row = userService.updateSecurityAnswer(userId, password, securityAnswer);
        if (row > 0) {
            result.put("code", 200);
            result.put("msg", "密保答案修改成功");
        } else if (row == -1) {
            result.put("code", 400);
            result.put("msg", "密码错误");
        } else if (row == -2) {
            result.put("code", 404);
            result.put("msg", "用户不存在");
        } else {
            result.put("code", 500);
            result.put("msg", "修改失败");
        }
        return result;
    }

    /**
     * 注销账号接口（未加密版本）
     */
    @PostMapping("/deleteAccount")
    public Map<String, Object> deleteAccount(@RequestBody Map<String, String> params) {
        Map<String, Object> result = new HashMap<>();

        // 解析参数
        Integer userId = params.get("id") != null ? Integer.parseInt(params.get("id")) : null;
        String password = params.get("password");

        // 参数校验
        if (userId == null || password == null || password.isEmpty()) {
            result.put("code", 400);
            result.put("msg", "参数不完整");
            return result;
        }

        // 调用服务层（未加密逻辑）
        int row = userService.deleteAccount(userId, password);
        if (row > 0) {
            result.put("code", 200);
            result.put("msg", "账号注销成功");
        } else if (row == -1) {
            result.put("code", 400);
            result.put("msg", "密码错误");
        } else if (row == -2) {
            result.put("code", 404);
            result.put("msg", "用户不存在");
        } else {
            result.put("code", 500);
            result.put("msg", "注销失败");
        }
        return result;
    }

}